package com.agent;


import lombok.extern.slf4j.Slf4j;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

/**
 * 实现字节码转换器
 */
@Slf4j
public class MonitoringTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(ClassLoader loader, String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) {
        //动态代理不处理
        if (className.contains("$$") || className.contains("BaseController")){
            return classfileBuffer;
        }
        //过滤需要监控的包
        if (!className.startsWith("com/platform/controller") && !className.startsWith("com/platform/service")) {
            return classfileBuffer;
        }
       // log.info("监控的类className：{}",className);
        ClassReader reader = new ClassReader(classfileBuffer);
        ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
        ClassVisitor visitor = new MonitoringClassVisitor(writer, className);
        reader.accept(visitor, ClassReader.EXPAND_FRAMES);
        return writer.toByteArray();
    }

}